<?php
class Actionrole_model extends TP_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->table = 'rel_role_action';
    }

    /**
     * getActionByRole function
     *
     * @Name getActionByRole
     * @Desc 获取当前角色action权限(兼容多角色问题)
     * @Author Pekey
     * @Date 2020-08-26
     * @param [type] $role
     * @return void
     */
    public function getActionByRole($role)
    {
        if (strpos($role, ',')) {
            $roles = explode(" ", $role);
        } else {
            $roles = $role;
        }

        $actions = array();
        if (is_array($roles)) {
            $conarr = array();
            $conarr['in'] = array('role_id', $roles);
            $datas = $this->get_list_full($conarr);
            foreach ($datas as $data) {
                if ($data['action_path'] != "") {
                    array_push($actions, $data['action_path']);
                }
            }
        } else {
            $datas = $this->get_list(array("role_id" => $roles));
            foreach ($datas as $data) {
                if ($data['action_path'] != "") {
                    array_push($actions, $data['action_path']);
                }
            }

        }

        return $actions;
    }

    /**
     * saveActionByRole function
     * 
     * @Name saveActionByRole
     * @Desc 保存角色action
     * @Author      LiAnXu
     * @Date 2020-11-25 11:23:51 星期三
     * @param  $role 角色id $data保存数据
     * @return boolean
     */
    public function saveActionByRole($role,$data)
    {   
        $arr['where']=sql_format('role_id={0}',$role);
        $arr['join']=array('tp_action','tp_action.path=tp_rel_role_action.action_path');
        $list=$this->get_list_full($arr);
        $list=array_column($list,'action_path');
        foreach ($data as $k => $v) {
            if(!in_array($v,$list)){
                $add[]=array('role_id'=>$role,'action_path'=>$v,'created'=>time());
            }            
        }
        foreach ($list as $k => $v) {
            if(!in_array($v,$data)){
                $update[$k]['data']=array('is_delete'=>1,'updated'=>time());
                $update[$k]['where']=array('action_path'=>$v);
            }
        }
        if(isset($add)){
            $this->add($add);
        }
        
        if(isset($update)){
            foreach ($update as $k => $v) {
                $this->update($v['data'],$v['where']);
            }
        }
        
        return;
        
    }

}
